<template>
	<view>
		<st-mc-framework :navTitle="ModuleTitle" @changeLevel="changeLevel" ref="framework"
			@AddModuleData_select='AddModuleData_select'>

			<template #content>
				<view class="content" style="height: 100%;width: 100%;">
					<view class="contentBox" style="flex: 1;">
						<view class="container TitleImageRelative">
							<view class="titleImage">
								<image src="../css/img/shenhe.png" v-show="readOnlyShow">
								</image>
							</view>



							<u--form class="u_form" labelPosition="left" :model="baseFormData" ref="uForm">
								<u-row justify="space-between" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="检验编号:">
											<u--input v-model="baseFormData.BillNO" placeholder="自动生成" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="产品名称:" @click="openBaseScreen('产品')"
											required>
											<u--input v-model="baseFormData.ProductName" placeholder="请选择产品名称" readonly
												border="none"></u--input>
											<u-icon slot="right" name="arrow-right"></u-icon>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="工序:" @click="addProcedure()" required>
											<u--input v-model="baseFormData.ProcedureName"
												:placeholder="!baseFormData.ProductName ?' 请先选择产品':'请选择工序'" readonly
												border="none"></u--input>
											<u-icon slot="right" name="arrow-right"></u-icon>
										</u-form-item>
									</u-col>
								</u-row>
								<u-row justify="space-between" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="检验日期:">
											<u--input v-model="baseFormData.BillDate" placeholder="自动带出检验日期" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="检验数量:" required>
											<u--input v-model="baseFormData.CkAmount" placeholder="请输入检验数量"
												type='number' @input="addCkAmount('检验')" :readonly='readOnlyShow'
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">

										<u-form-item labelWidth="auto" label="合格数量:">
											<u--input v-model="baseFormData.OkAmount" placeholder="自动带出合格数量" readonly
												type='number' @input="addAmount('合格')" border="none"></u--input>
										</u-form-item>
									</u-col>
								</u-row>

								<u-row justify="space-between" gutter="20">

									<u-col span="4">
										<u-form-item labelWidth="auto" label="不合格数量:">
											<u--input v-model="baseFormData.BadAmount" placeholder="自动带出不合格数量" readonly
												type='number' @input="addAmount('不合格')" border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="良率:">
											<u--input v-model="baseFormData.BadRate+'%'" placeholder="自动带出良率" readonly
												border="none"></u--input>

										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="检验结果:" @click="changeResultshow()"
											required>
											<u--input v-model="baseFormData.ResultName" placeholder="请选择检验结果" readonly
												border="none"></u--input>
											<u-icon slot="right" name="arrow-right"></u-icon>
										</u-form-item>
									</u-col>
								</u-row>

								<u-row justify="space-between" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="审核状态:">
											<u--input v-model="baseFormData.ApproveName" placeholder="自动带出审核状态" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="审核人:">
											<u--input v-model="baseFormData.Approver" placeholder="自动带出审核人" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="审核时间:">
											<u--input v-model="baseFormData.ApproveTime" placeholder="自动带出审核时间" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
								</u-row>

								<u-row justify="space-between" gutter="20">

									<u-col span="4">
										<u-form-item labelWidth="auto" label="检验员:" @click="openBaseScreen('人员')"
											required>
											<u--input v-model="baseFormData.QCEmplName" placeholder="请现选择检验员" readonly
												border="none"></u--input>
											<u-icon slot="right" name="arrow-right"></u-icon>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="检验类型:">
											<u--input v-model="baseFormData.FTypeName" placeholder="检验类型" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<view class="SOPView">
											<u-button size="small" text="查看SOP" @click="addSOP"></u-button>
										</view>
									</u-col>
								</u-row>


							</u--form>
						</view>
						<view class="table" v-show="CkAmountList.length>0">
							<table>
								<tr>
									<th>序号</th>
									<th>检验项目</th>
									<th>检验标准</th>
									<th>上极限</th>
									<th>下极限</th>
									<th>检验值</th>
									<th><text style="color: red;">*</text>检验结果</th>
								</tr>
								<tr v-for="(item, index) in CkAmountList">
									<td>{{index + 1}}</td>
									<td>
										<u--textarea v-model="item.FQCItemName" autoHeight border="none" disabled
											class="fixed-textarea"></u--textarea>
									</td>
									<td>

										<u--textarea v-model="item.JYBZ" autoHeight border="none" disabled
											class="fixed-textarea"></u--textarea>
									</td>
									<td>
										<u--textarea v-model="item.PoorWork" autoHeight border="none" disabled
											class="fixed-textarea"></u--textarea>
									</td>
									<td>
										<u--textarea v-model="item.PoorNormally" autoHeight border="none" disabled
											class="fixed-textarea"></u--textarea>
									</td>
									<td>
										<u--textarea v-model="item.JYJG" autoHeight border="none"
											@blur="JYJGInput(item,index)" :disabled='readOnlyShow'
											class="fixed-textarea"></u--textarea>
									</td>
									<td>
										<u--textarea v-model="item.ZFResultName" autoHeight border="none"
											@click="AddZFResult(index)" :disabled='readOnlyShow'
											class="fixed-textarea"></u--textarea>
									</td>
								</tr>
							</table>
						</view>
						<view class="table" v-show="tableData.length>0">
							<table>
								<tr>
									<th>序号</th>
									<th>检验项目</th>
									<th> <text style="color: red;">*</text>不合格数量</th>
								</tr>
								<tr v-for="(item, index) in tableData">
									<td>{{index + 1}}</td>
									<td>
										<u--textarea v-model="item.ReasonName" autoHeight border="none" disabled
											class="fixed-textarea"></u--textarea>
									</td>
									<td>
										<u-number-box class="u_number_box" v-model="item.BadNum" :min="0"
											:disabled="!buttonShow" @input='AddBadNumChild()'></u-number-box>
									</td>
								</tr>
							</table>

						</view>


					</view>

					<view class="DetailsbottomBtnsTow">
						<button class="button1" block @click="submit('保存')" v-show="submitShow">
							保存
						</button>
						<button v-if="ApproveBack('审核')" class="button2" block @click="toexamine" v-show="buttonShow">
							审核
						</button>
					</view>
				</view>
			</template>
		</st-mc-framework>
		<u-toast ref="uToast"></u-toast>
		<u-picker :show="JYJGshow" :columns="columns" @confirm="JYJGconfirm"></u-picker>
		<u-action-sheet :actions="Resultlist" :show="Resultshow" @select="ResultClick"
			@close="Resultshow=false"></u-action-sheet>
		<u-action-sheet :actions="ZFResultList" :show="ZFResultShow" @select="ZFResultClick"
			@close="ZFResultShow=false"></u-action-sheet>
		<u-action-sheet :actions="ProcedureList" :show="ProcedureShow" @select="Procedureclick"
			@close="ProcedureShow=false"></u-action-sheet>

		<u-modal :show="modalshow" :title="modaltitle" width="400" @confirm='modalconfirm' :showCancelButton='true'
			@cancel='modalshow=false'>
			<view class="slot-content">
				{{modalcontent}}
			</view>
		</u-modal>
		<m-loading :text="loadingName" v-model="showMLoading" :showClose="false"
			maskBackgroundColor="rgba(0,0,0,0.3)"></m-loading>

	</view>
</template>

<script>
	const open = uni.requireNativePlugin("Html5App-openFile");
	import {
		msg
	} from '../../common/comFun/utils';
	import {
		getTimeStamp,
		getFormatDateTime,
		getBefore7DateTime,
		formatDateTime,
		navigateMixin,
		baseAddModuleData_select,
		getchangeLevel
	} from '@/st_mes_zs/common/base.js';

	export default {
		mixins: [navigateMixin, baseAddModuleData_select],
		data() {
			return {


				readOnlyShow: false,
				baseFormData: {
					CheckupProductID: null,
					JobPROCID: 0,
					JobOrderID: 0,
					InspectionID: 0,
					BillNO: "",
					FType: "",
					ProductID: '',
					ProductName: "",
					BillDate: "",
					CkAmount: null,
					OkAmount: null,
					BadAmount: null,
					BadRate: null,
					Result: null,
					ResultName: '',
					Approve: null,
					ApproveName: '',
					Approver: null,
					ApproveTime: null,
					PGBillNo: "",
					QCEmplID: '',
					QCEmplName: "",
					ProcedureID: '',
					ProcedureName: '',
					EquipmentID: null
				},
				// 判断结果
				sexs: [{
					text: '合格',
					value: 1
				}, {
					text: '不合格',
					value: -1
				}],
				tableData: [],
				CkAmountList: [],
				routeIndex: 0,
				JYJGshow: false,
				// 子标的
				columns: [
					['合格', '不合格']
				],
				JYJGshowIndex: 0,
				Resultshow: false,
				Resulttitle: '',
				Resultlist: [],

				buttonShow: true,
				submitShow: true,
				ProcedureShow: false,
				ProcedureList: [],
				BtnApprove: [],


				FWorkshopID: null,
				ModuleTitle: '', //标题
				showMLoading: false,
				loadingName: '正在加载中……',
				modalshow: false,
				modaltitle: '提示',
				modalcontent: '',
				ZFResultIndex: null,
				ZFResultShow: false,
				// 判断结果
				ZFResultList: [{
					name: '合格',
					id: 1
				}, {
					name: '不合格',
					id: -1
				}],

			};
		},
		onReady() {
			var that = this
			uni.hideLoading();
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = that.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;
			that.FWorkshopID = MesBasicInfo.FWorkshopID;
			that.ModuleTitle = appConfigInfo.ActiveModule.ModuleName

			let foundNode = null;
			for (const module of this.$store.state.appConfigInfo.ModuleInfo_All) {
				if (module.TreeTypeName === '生产检验') {
					for (const node of module.Node) {
						if (node.APFunName === '巡检') {
							foundNode = JSON.parse(JSON.stringify(node));
							break; // 找到后立即退出内层循环  
						}
					}
					if (foundNode) {
						break;
					}
				}
			}
			this.BtnApprove = foundNode['IconApprove'];
		},

		onLoad(onload) {
			var that = this
			that.$safeStatus({
				payload: '其他', // 要传递的数据
			});
			// 缓存状态引用
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = this.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;

			// 统一处理加载状态
			const setLoading = (state) => this.showMLoading = state;
			if (onload.item) {
				var item = JSON.parse(onload.item)
				that.baseFormData = item
			}
			// 主处理逻辑
			if (that.baseFormData.InspectionID) {
				setLoading(true);
				this.queryList(that.baseFormData.InspectionID);
				return;
			}
			// 统一处理表单默认值
			const formDefaults = {
				BadRate: 0,
				BadAmount: 0,
				FTypeName: '巡检',
				BillDate: getFormatDateTime(new Date()),
				QCEmplName: UserInfo.EmplName,
				QCEmplID: UserInfo.EmplID,
				EquipmentID: MesBasicInfo.warehouse.EquipmentID,

			};
			this.assignFormData(this.baseFormData, formDefaults);
			setLoading(false);


		},
		onBackPress(options) { // 监听页面返回
			if (options.from == 'navigateBack') { // 通过点击路由返回
				return false;
			} else if (options.from == 'backbutton') { // 通过外置返回 
				return true;
			}
		},
		onShow() {
			var that = this
			uni.$on('refreshDetail', (res) => {
				that.getValue(res.data); // 调用目标方法
			});
		},
		onUnload() {
			uni.$off('refreshDetail');
		},
		methods: {
			modalconfirm() {
				var that = this
				that.modalshow = false
				if (that.modaltitle == '审核') {
					that.submit('审核')
				}
			},
			// 创建表单赋值工具函数
			assignFormData(target, defaults = {}) {
				Object.keys(defaults).forEach(key => {
					Vue.set(target, key, defaults[key]);
				});
				this.$forceUpdate();
			},
			async AddModuleData_select(res) {
				try {
					const backDelta = await this.GetModuleData_select(res);
				} catch (error) {
					console.error('返回操作失败:');
				}
			},
			showModal(title, content) {
				this.modaltitle = title;
				this.modalcontent = content;
				this.modalshow = true;
			},



			AddBadNumChild() {
				var num = 0
				this.tableData.forEach(item => {
					num = num + item.BadNum
				})
				this.baseFormData.BadAmount = num
				this.addAmount('不合格')
				this.$forceUpdate()
			},
			ApproveBack(str) {
				let that = this;
				let Type = false;
				if (that.BtnApprove.length) {
					Type = that.BtnApprove.some(item => {
						return item.MenuName == str
					})
				}
				return Type;
			},
			addProcedure() {
				var that = this
				if (!that.readOnlyShow && that.baseFormData.ProductID) {
					that.Request.request('getProcedureByProduct', {
						ProductID: that.baseFormData.ProductID,
						FWorkshopID: that.FWorkshopID
					}, (ret) => {
						console.log(ret.data.ds);
						ret.data.ds.map(item => item.name = item.ProcedureName)
						that.ProcedureList = ret.data.ds
						that.ProcedureShow = true
						that.$forceUpdate()
					})
				}

			},
			addCkAmount() {
				var that = this
				if (Number(that.FPlanQty) < Number(that.baseFormData.CkAmount)) {
					that.showModal('报错', '检验数量不能大于派工数量');
					const formDefaults = {
						CkAmount: 0
					};
					this.assignFormData(this.baseFormData, formDefaults)
				}
				that.addAmount('不合格')

			},
			addAmount(str) {
				const that = this;
				const formDefaults = {};
				const {
					CkAmount,
					OkAmount: qualifiedAmount,
					BadAmount: defectiveAmount
				} = that.baseFormData;

				// 统一校验函数
				const validateNumber = (value, min = 0, max = CkAmount) => {
					const num = Number(value);
					if (num < min) return `不能小于${min}`;
					if (num > max) return `不能大于检验数量`;
					return null;
				};

				// 核心计算逻辑
				const calculateFields = () => {
					if (str === '合格') {
						formDefaults.BadAmount = Number(CkAmount) - Number(qualifiedAmount);
					} else {
						formDefaults.OkAmount = Number(CkAmount) - Number(defectiveAmount);
					}
					// 避免除以零
					formDefaults.BadRate = Number(CkAmount) > 0 ?
						((Number(formDefaults.OkAmount || qualifiedAmount) / Number(CkAmount)) * 100).toFixed(2) :
						0;
				};

				// 主逻辑处理
				switch (str) {
					// case '合格':
					// 	if (CkAmount == null || CkAmount <= 0) {
					// 		that.showModal('报错', '检验数量必须大于0', '确认', '取消');
					// 		break;
					// 	}

					// 	const okError = validateNumber(qualifiedAmount);
					// 	if (okError) {
					// 		that.showModal('报错', `合格数量${okError}`, '确认', '取消');
					// 		formDefaults.OkAmount = 0;
					// 		formDefaults.BadAmount = 0;
					// 		that.resettableData()
					// 	} else {
					// 		calculateFields();
					// 	}
					// 	break;

					case '不合格':
						// if (CkAmount == null || CkAmount <= 0) {
						// 	that.showModal('报错', '请先输入检验数量', '确认', '取消');
						// 	break;
						// }
						const defectiveError = validateNumber(defectiveAmount);
						if (defectiveError) {
							that.showModal('报错', `不合格数量${defectiveError}`, '确认', '取消');
							formDefaults.BadAmount = 0;
							formDefaults.OkAmount = CkAmount;
							formDefaults.BadRate = 100;
							that.resettableData()
						} else {
							calculateFields();
						}
						break;
					default:
						console.warn('未知操作类型:', str);
						return;
				}
				// 统一更新数据
				that.UpdateAssignFormData(formDefaults);
			},
			resettableData() {
				var that = this
				setTimeout(() => {
					that.tableData.forEach(item => {
						item.BadNum = 0
					})

					that.$forceUpdate()
				}, 500)

			},
			UpdateAssignFormData(formDefaults) {
				this.assignFormData(this.baseFormData, formDefaults)
			},
			// addAmount(str) {
			// 	var that = this
			// 	var show = true
			// 	if (str == '合格') {

			// 		if (Number(that.baseFormData.CkAmount) < Number(that.baseFormData.OkAmount)) {

			// 			that.showModal('报错', '合格数量不能大于检验数量');



			// 			that.baseFormData.OkAmount = 0
			// 			that.baseFormData.BadAmount = that.baseFormData.CkAmount
			// 			that.$forceUpdate()

			// 		} else if (Number(that.baseFormData.OkAmount) < 0) {
			// 			that.showModal('报错', '合格数量不能小于0');



			// 			that.baseFormData.OkAmount = 0
			// 			that.baseFormData.BadAmount = that.baseFormData.CkAmount
			// 			that.$forceUpdate()
			// 		} else {
			// 			that.baseFormData.BadAmount = Number(that.baseFormData.CkAmount) - Number(that.baseFormData
			// 				.OkAmount)
			// 			that.$forceUpdate()
			// 		}
			// 	} else {

			// 		if (Number(that.baseFormData.CkAmount) < Number(that.baseFormData.BadAmount)) {
			// 			if (that.baseFormData.CkAmount != '') {
			// 				that.showModal('报错', '不合格数量不能大于检验数量');



			// 				that.baseFormData.BadAmount = 0
			// 				that.baseFormData.OkAmount = that.baseFormData.CkAmount
			// 				setTimeout(() => {
			// 					that.tableData.forEach(item => {
			// 						item.BadNum = 0
			// 					})
			// 					that.baseFormData.BadRate = 0
			// 					that.$forceUpdate()
			// 				}, 500)
			// 				that.$forceUpdate()
			// 			}
			// 		} else if (Number(that.baseFormData.BadAmount) < 0) {

			// 			that.showModal('报错', '不合格数量不能小于0');



			// 			that.baseFormData.BadAmount = 0
			// 			that.baseFormData.OkAmount = that.baseFormData.CkAmount

			// 			setTimeout(() => {
			// 				that.tableData.forEach(item => {
			// 					item.BadNum = 0
			// 				})
			// 				that.baseFormData.BadRate = 0
			// 				that.$forceUpdate()
			// 			}, 500)
			// 		} else {
			// 			that.baseFormData.BadAmount = that.baseFormData.BadAmount ? that.baseFormData.BadAmount : 0
			// 			that.baseFormData.OkAmount = Number(that.baseFormData.CkAmount) - Number(that.baseFormData
			// 				.BadAmount)
			// 			if (Number(that.baseFormData.CkAmount) > 0) {
			// 				that.baseFormData.BadRate = ((Number(that.baseFormData.BadAmount) / Number(that
			// 					.baseFormData.CkAmount)) * 100).toFixed(2)
			// 			}
			// 			that.$forceUpdate()
			// 		}
			// 	}


			// },
			Procedureclick(e) {
				var that = this
				console.log(e);


				var formDefaults = {
					ProcedureID: e.ProcedureID,
					ProcedureName: e.ProcedureName,
				};
				that.assignFormData(that.baseFormData, formDefaults)
				that.ProcedureShow = false
				that.Request.request('getJYItemsByProductID', {
					ProductID: e.ProcedureID,
					FWorkshopID: that.FWorkshopID,
					InspectionName: '巡检'
				}, (ret) => {
					console.log(ret);
					ret.data.ds2.map(item => {
						item.BadNum = 0
					})
					if (ret.data.ds.length > 0) {
						that.baseFormData.CheckupProductID = ret.data.ds[0].CheckupProductID
					}
					if (ret.data.ds1.length > 0) {
						that.CkAmountList = ret.data.ds1
					}
					if (ret.data.ds2.length > 0) {
						that.tableData = ret.data.ds2
					}

				})

			},
			JYJGInput(ite, iteIndex) {
				var that = this
				var formDefaults = {}
				if (ite.PoorWork && ite.PoorNormally) {
					if (Number(ite.JYJG)) {
						if (Number(ite.PoorWork) > Number(ite.JYJG) || Number(ite.PoorNormally) < Number(ite
								.JYJG)) {
							formDefaults = {
								ZFResult: that.ZFResultList[1].id,
								ZFResultName: that.ZFResultList[1].name,
							}
						} else {
							formDefaults = {
								ZFResult: that.ZFResultList[0].id,
								ZFResultName: that.ZFResultList[0].name,
							}
						}
					}

				}
				that.assignFormData(that.CkAmountList[iteIndex], formDefaults);
				that.$forceUpdate()
			},
			getValue(payload) {
				var that = this;
				console.log(payload);
				that.showMLoading = false
				const {
					type,
					...data
				} = payload;
				if (payload === '返回') return;
				const typeHandlers = {
					'人员': () => ({
						QCEmplID: data.UserID,
						QCEmplName: data.UserName,

					}),
					'产品': () => ({
						ProductName: data.ProductName,
						ProductID: data.ProductID
					}),
					'原材料': () => ({
						ProductName: data.ProductName,
						ProductID: data.ProductID
					}),
				};
				if (typeHandlers[type]) {
					if (type == '原材料') {
						Object.assign(that.tableData[that.tableDataIndex], typeHandlers[type]());
					} else {
						Object.assign(that.baseFormData, typeHandlers[type]());
					}
				}
				console.log(this.baseFormData);
				this.$forceUpdate()
			},

			openBaseScreen(str) {
				var that = this;
				var obj;
				if (!that.readOnlyShow) {
					if (str == '人员') {
						obj = {
							cmd: 'getEmplByJobName',
							type: str,
							serverSearch: {
								isPaging: true, //是否分页
								pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中		
								searchShow: false, //是否查询
								searchKey: 'searchKey', //搜索关键词，应包含在param中
								showText: 'UserName', //查询结果显示的字段
							},
							param: {
								JobName: '',
								PageIndex: 1,
								PageSize: 30
							}
						}
					} else if (str == '产品') {
						obj = {
							cmd: 'ZS_getProductList',
							type: str,
							serverSearch: {
								isPaging: true, //是否分页
								pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中		
								searchShow: false, //是否查询
								searchKey: 'ProductName', //搜索关键词，应包含在param中
								showText: 'ProductName', //查询结果显示的字段
							},
							param: {
								EquipmentID: that.baseFormData.EquipmentID,
								PageIndex: 1,
								PageSize: 30
							}
						}
					}

					uni.navigateTo({
						url: `../common/baseScreen?obj=${JSON.stringify(obj)}`,
						animationType: 'slide-in-right',
						animationDuration: 300
					});
				}

			},




			addSOP() {
				var that = this

				try {
					that.Request.request('getProductSOP', {
						ProcedureID: that.baseFormData.ProcedureID,
						ProductID: that.baseFormData.ProductID
					}, (ret) => {
						that.loadingName = '正在打开中…'
						that.showMLoading = true
						console.log(ret.data);
						if (ret.status == 200) {
							if (ret.data.ds.length > 0) {
								var url = that.Request.IPAgreement() + that.Request.serverIP() + ret.data.ds[0]
									.FileName
								console.log(url);
								uni.downloadFile({
									url: url,
									success: function(res) {
										if (res.tempFilePath) {
											var filePath = plus.io.convertLocalFileSystemURL(res
												.tempFilePath);
											console.log(JSON.stringify(filePath))
											open.openFile({
												filename: filePath,
												title: 'SOP查看',
												isShowBackIcon: true
											}, ret => {
												that.showMLoading = false
											});
										} else {

											that.changeshowToast()
										}

									}
								})
							} else {
								that.changeshowToast()
							}
						}
					})
				} catch (e) {
					console.log(e)
					that.$utils.hideLoading();
					that.$utils.msg('请求失败请重试')
				}
			},
			changeshowToast() {
				var that = this;
				that.showMLoading = false
				uni.showToast({
					title: '暂无此文档',
					icon: 'error',
					duration: 2000
				})
			},
			ResultClick(e) {
				var that = this
				console.log(e);
				var formDefaults = {
					ResultName: e.name,
					Result: e.ID
				}
				that.UpdateAssignFormData(formDefaults)
				that.Resultshow = false
			},

			changeResultshow() {
				var that = this
				if (!that.readOnlyShow) {

					that.Request.request('getJYResult', {
						FType: '首件检验'
					}, (ret) => {
						console.log(ret.data);
						if (ret.status == 200) {
							that.Resultlist = ret.data.ds
							that.Resultlist.map(item => {
								item.name = item.NAME
							})
							that.Resultshow = true
						}
					})
				}


			},
			JYJGconfirm(e) {
				var name = e.value[0]
				var num
				this.JYJGshow = false
				if (name == '合格') {
					num = 1
				} else {
					num = -1
				}
				this.tableData[this.JYJGshowIndex].JYJG = num
				this.tableData[this.JYJGshowIndex].JYJGName = name

			},

			toexamine() {
				var that = this
				that.showModal('审核', '确定审核吗?');
			},
			submit(str) {
				var that = this
				var show = true
				var msg
				var tableDataAll = JSON.parse(JSON.stringify(that.tableData))
				var CkAmountListAll = JSON.parse(JSON.stringify(that.CkAmountList))
				const {
					ResultName,
					CkAmount,
					BadAmount,
					OkAmount,
				} = that.baseFormData;

				if (CkAmount == '' || CkAmount == null) {
					msg = '请输入检验数量'
					show = false
				} else if (ResultName == '' || ResultName == null) {
					msg = '请输入检验结果'
					show = false
				} else if (Number(BadAmount) == 0) {
					show = true
				} else if (Number(OkAmount) == 0) {
					show = true
				} else if (BadAmount == '' || BadAmount == null) {
					msg = '请输入不合格数量'
					show = false
				} else if (OkAmount == '' || OkAmount == null) {
					msg = '请输入合格数量'
					show = false
				}
				CkAmountListAll.some((item, index) => {
					if (item.PoorNormally || item.PoorWork) {
						if (!item.JYJG) {
							msg = `请输入第${index + 1}行检验值`;
							show = false;
							return true;
						}
					}
					if (item.ZFResult == '' || item.ZFResult == null) {
						msg = '请选择检验结果';
						show = false;
					}
					return false; // 继续遍历下一个
				});

				if (show) {
					that.SubmitBtn(str, tableDataAll, CkAmountListAll)
				} else {
					that.showModal('报错', msg);
				}
			},
			SubmitBtn(str, tableDataAll, CkAmountListAll) {
				var that = this
				var cmd
				const {
					ResultName,
					CkAmount,
					BadAmount,
					OkAmount,
					ProductName,
					ProductID,
					QCEmplID,
					JobPROCID,
					Result,
					ProcedureID,
					JobOrderID,
					QCEmplName
				} = that.baseFormData;
				tableDataAll.forEach(item => {
					if (item.PoorWork == '' || item.PoorWork == null) {
						item.PoorWork = '@'
					}
					if (item.PoorNormally == '' || item.PoorNormally == null) {
						item.PoorNormally = '@'
					}
					if (item.JYJG == '' || item.JYJG == null) {
						item.JYJG = '@'
					}
				})
				CkAmountListAll.forEach(item => {
					if (item.JYJG == '' || item.JYJG == null) {
						item.JYJG = '@'
					}
					if (item.JYBZ == '' || item.JYBZ == null) {
						item.JYBZ = '@'
					}
					if (item.PoorWork == '' || item.PoorWork == null) {
						item.PoorWork = '@'
					}
					if (item.PoorNormally == '' || item.PoorNormally == null) {
						item.PoorNormally = '@'
					}
				})
				that.baseFormData.InspectionID = that.baseFormData.InspectionID ? that.baseFormData.InspectionID : 0
				var obj = {
					CkAmount: CkAmount,
					InspectionID: that.baseFormData.InspectionID,
					ProductName: ProductName,
					ProductID: ProductID,
					QCEmplID: QCEmplID,
					JobPROCID: JobPROCID,
					FType: 'XJ',
					FResult: Result,
					ProcedureID: ProcedureID,
					BadAmount: BadAmount,
					JobOrderID: JobOrderID,
					JYJG: CkAmountListAll.map(item => item.JYJG).join(','),
					CheckupProductCodeDeID: CkAmountListAll.map(item => item.CheckupProductCodeDeID)
						.join(','),
					ZFResult: CkAmountListAll.map(item => item.ZFResult).join(','),
					JYBZ: CkAmountListAll.map(item => item.JYBZ).join(','),
					PoorWork: CkAmountListAll.map(item => item.PoorWork).join(','),
					PoorNormally: CkAmountListAll.map(item => item.PoorNormally).join(','),
					UpID: CkAmountListAll.map(item => item.UpID).join(','),
					FQCItemID: CkAmountListAll.map(item => item.FQCItemID).join(','),
					CheckupProductID: that.baseFormData.CheckupProductID,
					BadReasonID: tableDataAll.map(item => item.BadReasonID).join(','),
					BadNum: tableDataAll.map(item => item.BadNum).join(','),
					CheckupProductCodeDefectDeID: tableDataAll.map(item => item
							.CheckupProductCodeDefectDeID)
						.join(','),

				}
				if (that.baseFormData.InspectionID == 0) {
					cmd = 'insertJYRecord'
				} else {
					cmd = 'saveJYRecord'
					obj.InspectionDefectDeID = tableDataAll.map(item => item.InspectionDefectDeID).join(',')
					obj.InspectionDeID = CkAmountListAll.map(item => item.InspectionDeID).join(',')
				}
				console.log(obj);
				that.Submitmodifications(str, cmd, obj)
			},
			Submitmodifications(str, cmd, obj) {
				var that = this
				try {
					that.Request.request(cmd, obj, (ret) => {
						console.log(ret.data);
						if (ret.status == 200) {
							var NewInspectionID
							if (ret.data && ret.data.ds) {
								NewInspectionID = ret.data.ds[0].InspectionID
							} else {
								NewInspectionID = that.baseFormData.InspectionID
							}
							that.$refs.uToast.show({
								title: '保存',
								type: 'success',
								message: '保存成功'
							})
							switch (str) {
								case '审核':
									var obj1 = {
										InspectionID: NewInspectionID,
										QCEmplName: that.baseFormData.QCEmplName
									}
									that.Request.request('ApproveJY', obj1, (res) => {
										console.log(res);
										if (res.status == 200) {
											that.$refs.uToast.show({
												title: '审核',
												type: 'success',
												message: '审核成功'
											})
											setTimeout(() => {
												that.queryList(NewInspectionID)
											}, 1000)
										}
									})
									break;
								default:
									setTimeout(() => {
										that.queryList(NewInspectionID)
									}, 1000)
							}

						}
					})
				} catch (e) {
					console.log(e)
					this.$utils.hideLoading();
					this.$utils.msg('请求失败请重试')
				}
			},
			// submit(str) {
			// 	var that = this
			// 	var show = true
			// 	var msg
			// 	var cmd
			// 	var tableDataAll = JSON.parse(JSON.stringify(that.tableData))
			// 	var CkAmountListAll = JSON.parse(JSON.stringify(that.CkAmountList))
			// 	if (that.baseFormData.CkAmount == '' || that.baseFormData.CkAmount == null) {
			// 		msg = '请输入检验数量'
			// 		show = false
			// 	} else if (that.baseFormData.ResultName == '' || that.baseFormData.ResultName == null) {
			// 		msg = '请输入检验结果'
			// 		show = false
			// 	} else if (Number(that.baseFormData.BadAmount) == 0) {
			// 		show = true
			// 	} else if (Number(that.baseFormData.OkAmount) == 0) {
			// 		show = true
			// 	} else if (that.baseFormData.BadAmount == '' || that.baseFormData.BadAmount == null) {
			// 		msg = '请输入不合格数量'
			// 		show = false
			// 	} else if (that.baseFormData.OkAmount == '' || that.baseFormData.OkAmount == null) {
			// 		msg = '请输入合格数量'
			// 		show = false
			// 	}
			// 	CkAmountListAll.some((item, index) => {
			// 		if (item.PoorNormally || item.PoorWork) {
			// 			console.log('防护');
			// 			if (!item.JYJG) {
			// 				console.log('防护');
			// 				msg = `请输入第${index + 1}行检验值`;
			// 				show = false;
			// 				return true;
			// 			}
			// 		}
			// 		if (item.ZFResult == '' || item.ZFResult == null) {
			// 			msg = '请选择检验结果';
			// 			show = false;
			// 		}
			// 		return false; // 继续遍历下一个
			// 	});


			// 	if (show) {
			// 		tableDataAll.forEach(item => {
			// 			if (item.PoorWork == '' || item.PoorWork == null) {
			// 				item.PoorWork = '@'
			// 			}
			// 			if (item.PoorNormally == '' || item.PoorNormally == null) {
			// 				item.PoorNormally = '@'
			// 			}
			// 			if (item.JYJG == '' || item.JYJG == null) {
			// 				item.JYJG = '@'
			// 			}
			// 		})
			// 		CkAmountListAll.forEach(item => {
			// 			if (item.JYJG == '' || item.JYJG == null) {
			// 				item.JYJG = '@'
			// 			}
			// 			if (item.JYBZ == '' || item.JYBZ == null) {
			// 				item.JYBZ = '@'
			// 			}
			// 			if (item.PoorWork == '' || item.PoorWork == null) {
			// 				item.PoorWork = '@'
			// 			}
			// 			if (item.PoorNormally == '' || item.PoorNormally == null) {
			// 				item.PoorNormally = '@'
			// 			}
			// 		})


			// 		that.baseFormData.InspectionID = that.baseFormData.InspectionID ? that.baseFormData.InspectionID : 0


			// 		var obj = {
			// 			CkAmount: that.baseFormData.CkAmount,
			// 			InspectionID: that.baseFormData.InspectionID,
			// 			ProductName: that.baseFormData.ProductName,
			// 			ProductID: that.baseFormData.ProductID,
			// 			QCEmplID: that.baseFormData.QCEmplID,
			// 			JobPROCID: that.baseFormData.JobPROCID,
			// 			FType: 'XJ',
			// 			FResult: that.baseFormData.Result,
			// 			ProcedureID: that.baseFormData.ProcedureID,
			// 			BadAmount: that.baseFormData.BadAmount,
			// 			JobOrderID: that.baseFormData.JobOrderID,
			// 			JYJG: CkAmountListAll.map(item => item.JYJG).join(','),
			// 			CheckupProductCodeDeID: CkAmountListAll.map(item => item.CheckupProductCodeDeID)
			// 				.join(','),
			// 			ZFResult: CkAmountListAll.map(item => item.ZFResult).join(','),
			// 			JYBZ: CkAmountListAll.map(item => item.JYBZ).join(','),
			// 			PoorWork: CkAmountListAll.map(item => item.PoorWork).join(','),
			// 			PoorNormally: CkAmountListAll.map(item => item.PoorNormally).join(','),
			// 			UpID: CkAmountListAll.map(item => item.UpID).join(','),
			// 			FQCItemID: CkAmountListAll.map(item => item.FQCItemID).join(','),
			// 			CheckupProductID: that.baseFormData.CheckupProductID,
			// 			BadReasonID: tableDataAll.map(item => item.BadReasonID).join(','),
			// 			BadNum: tableDataAll.map(item => item.BadNum).join(','),
			// 			CheckupProductCodeDefectDeID: tableDataAll.map(item => item
			// 					.CheckupProductCodeDefectDeID)
			// 				.join(','),

			// 		}
			// 		if (that.baseFormData.InspectionID == 0) {
			// 			cmd = 'insertJYRecord'
			// 		} else {
			// 			cmd = 'saveJYRecord'
			// 			obj.InspectionDefectDeID = tableDataAll.map(item => item.InspectionDefectDeID).join(',')
			// 			obj.InspectionDeID = CkAmountListAll.map(item => item.InspectionDeID).join(',')
			// 		}
			// 		that.Request.request(cmd, obj, (ret) => {
			// 			console.log(ret.data);
			// 			if (ret.status == 200) {
			// 				var InspectionID
			// 				if (ret.data && ret.data.ds) {
			// 					InspectionID = ret.data.ds[0].InspectionID
			// 				} else {
			// 					InspectionID = that.baseFormData.InspectionID
			// 				}
			// 				that.$refs.uToast.show({
			// 					title: '保存',
			// 					type: 'success',
			// 					message: '保存成功'
			// 				})
			// 				if (str == '审核') {
			// 					var obj1 = {
			// 						InspectionID: InspectionID,
			// 						QCEmplName: that.baseFormData.QCEmplName
			// 					}
			// 					that.Request.request('ApproveJY', obj1, (res) => {
			// 						if (res.status == 200) {
			// 							that.$refs.uToast.show({
			// 								title: '审核',
			// 								type: 'success',
			// 								message: '审核成功'
			// 							})
			// 							setTimeout(() => {
			// 								that.queryList(InspectionID)
			// 							}, 1000)
			// 						}

			// 					})
			// 				} else {
			// 					setTimeout(() => {
			// 						that.queryList(InspectionID)
			// 					}, 1000)
			// 				}
			// 			}
			// 		})
			// 	} else {

			// 		that.showModal('报错', msg);



			// 	}
			// },


			ZFResultClick(e) {
				var that = this
				var formDefaults = {
					ZFResult: e.id,
					ZFResultName: e.name
				}
				console.log(formDefaults);
				that.assignFormData(that.CkAmountList[that.ZFResultIndex], formDefaults);
				that.ZFResultShow = false
			},
			AddZFResult(index) {
				var that = this
				that.ZFResultIndex = index
				that.ZFResultShow = true
			},

			getTarget(arrayName, status) {
				// 1. 根据arrayName获取对应数组
				const targetArray = this[arrayName];
				// 2. 在目标数组中查找
				const obj = targetArray.find(item => item.id === status);
				return obj.name || '';
			},
			queryList(id) {
				var that = this
				try {
					that.Request.request('getInspectionDetail', {
						InspectionID: id
					}, (ret) => {
						console.log(ret);
						that.showMLoading = false
						if (ret.status == 200) {

							const [firstItem] = ret.data.ds;
							that.baseFormData = firstItem
							that.FPlanQty = firstItem.FPlanQty
							const formDefaults = {
								ApproveTime: formatDateTime(firstItem.ApproveTime),
								OkAmount: firstItem.OkAmount ?? 0,
								BadAmount: firstItem.BadAmount ?? 0,
								FTypeName: firstItem.FTypeName ?? '巡检',
							};
							that.assignFormData(that.baseFormData, formDefaults)

							const {
								ApproveName
							} = that.baseFormData;
							that.readOnlyShow = ApproveName === '已审核';
							that.buttonShow = !that.readOnlyShow;
							that.submitShow = !that.readOnlyShow;
							ret.data.ds1.map((item) => {
								item.ZFResultName = that.getTarget('ZFResultList', item.ZFResult)
							})
							ret.data.ds2.forEach(item => {
								if (item.BadNum == null) {
									item.BadNum = 0;
								}
							});
							that.CkAmountList = ret.data.ds1
							that.tableData = ret.data.ds2

						}

					}, (err) => {
						that.showMLoading = false
					})
				} catch (e) {
					that.showMLoading = false
					console.log(e)
					this.$utils.hideLoading();
					this.$utils.msg('请求失败请重试')
				}
			},

			changeLevel(list, data, row) {
				getchangeLevel(data)
				uni.$emit('refreshList');
			},
		}
	}
</script>

<style lang="scss" >
	@import "../css/index.css";

	.SOPView {
		flex: 1;
		box-sizing: border-box;

		.u-button {
			width: 10%;
			float: right;
			color: #fff;
			background-color: #51d0d0;
			margin-top: 5px;
			box-sizing: border-box;
		}
	}
</style>